package com.hildeberto.versions.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: htmfilho
 * Date: 8/2/13
 * Time: 10:43 AM
 * To change this template use File | Settings | File Templates.
 */
public enum CommandLine {

    MANAGER;

    public String getResult(String command) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = executeCommand(command);

            String line = reader.readLine();
            while (line != null) {
                sb.append(line);
                line = reader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public List<String> getResultLines(String command) {
        List<String> lines = new ArrayList<>();
        try {
            BufferedReader reader = executeCommand(command);

            String line = reader.readLine();
            while (line != null) {
                lines.add(line);
                line = reader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    private BufferedReader executeCommand(String command) throws IOException {
        try {
            Process p = Runtime.getRuntime().exec(command);
            p.waitFor();
            return new BufferedReader(new InputStreamReader(p.getInputStream()));
        }
        catch(InterruptedException ie) {
            return null;
        }
    }
}
